package com.oasystem.web.controller.configuration;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.oasystem.domain.Department;
import com.oasystem.domain.Goods;
import com.oasystem.domain.Operator;
import com.oasystem.domain.PagingBean;
import com.oasystem.domain.Permission;
import com.oasystem.service.BackupDBService;
import com.oasystem.service.DepartmentService;
import com.oasystem.service.GoodsService;
import com.oasystem.service.MemberService;
import com.oasystem.service.OperatorService;
import com.oasystem.service.PermissionService;
import com.oasystem.utils.BackupConfigUtil;
import com.oasystem.utils.BackupFilesUtils;

@Controller
@RequestMapping(value = "/MainMenu/configuration")
public class ConfigurationController {

	@Resource(name = "operatorService")
	private OperatorService operatorService;
	@Resource(name = "permissionService")
	private PermissionService permissionService;
	@Resource(name = "goodsService")
	private GoodsService goodsService;
	@Resource(name = "departmentService")
	private DepartmentService departmentService;
	@Resource(name = "memberService")
	private MemberService memberService;
	
	@RequestMapping(value = "/operatorPage")
	public String operatorPage(Model model) {
		model.addAttribute("mainMenu", "configuration");
		model.addAttribute("subMenu", "operator");
		model.addAttribute("operator", new Operator());
		model.addAttribute("permissionList", permissionService.getAll());
		return "configuration.operatorPage";
	}

	@RequestMapping(value = "/goodsPage")
	public String goodsPage(Model model) {
		model.addAttribute("mainMenu", "configuration");
		model.addAttribute("subMenu", "goods");
		model.addAttribute("goods", new Goods());
		return "configuration.goodsPage";
	}

	@RequestMapping(value = "/departmentPage")
	public String departmentPage(Model model) {
		model.addAttribute("mainMenu", "configuration");
		model.addAttribute("subMenu", "department");
		model.addAttribute("department", new Department());
		return "configuration.departmentPage";
	}

	@RequestMapping(value = "/dataSafePage")
	public String dataSafePage(Model model) {
		model.addAttribute("mainMenu", "configuration");
		model.addAttribute("subMenu", "dataSafe");
		model.addAttribute("backupInterval",BackupDBService.hour);
		model.addAttribute("backupFileList", BackupFilesUtils.getBackupFileList(20));
		model.addAttribute("message",BackupDBService.isRunningBackup()?"备份功能已经开启":"备份功能未开启");
		model.addAttribute("isRunningBackup",BackupDBService.isRunningBackup());
		return "configuration.dataSafePage";
	}
	@RequestMapping(value = "/stopBackup")
	public String stopBackup(Model model) {
		model.addAttribute("mainMenu", "configuration");
		model.addAttribute("subMenu", "dataSafe");
		model.addAttribute("backupInterval", BackupConfigUtil.getParam("hour"));
		model.addAttribute("backupFileList", BackupFilesUtils.getBackupFileList(20));
		BackupDBService.stopBackup();
		model.addAttribute("message","已经停止备份");
		model.addAttribute("isRunningBackup",BackupDBService.isRunningBackup());
		return "configuration.dataSafePage";
	}
	
	@RequestMapping(value = "/restore")
	public @ResponseBody
	ModelMap restore(String fileName,Model model) {
		ModelMap map = new ModelMap();
		try {
			BackupDBService.restore(fileName);
			map.addAttribute("message", "恢复成功");
		} catch (IOException e) {
			map.addAttribute("message", "恢复失败，请联系管理员");
			e.printStackTrace();
		}
		return map;
	}
	
	@RequestMapping(value = "/saveBackupConfig")
	public String saveBackupConfig(String hour,Model model) {
		model.addAttribute("mainMenu", "configuration");
		model.addAttribute("subMenu", "dataSafe");
		model.addAttribute("backupFileList", BackupFilesUtils.getBackupFileList(20));
		if(hour==null || hour.equals("")){
			model.addAttribute("message","时间格式有误");
			return "configuration.dataSafePage";
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("hour", hour);
		BackupDBService.hour=hour;
		BackupDBService.update(Integer.valueOf(hour)*60*60*1000);
		model.addAttribute("backupInterval", BackupDBService.hour);
		model.addAttribute("message","开启成功，以后每隔"+hour+"小时后进行备份");
		model.addAttribute("isRunningBackup",BackupDBService.isRunningBackup());
		return "configuration.dataSafePage";
	}

	@RequestMapping(value = "/insertOperator", method = RequestMethod.POST)
	public @ResponseBody
	ModelMap insertOperator(@ModelAttribute("operator") Operator operator,
			String[] permissionID) {

		for (String id : permissionID) {
			Permission permission = new Permission();
			permission.setPermissionID(Integer.valueOf(id));
			operator.getPermissions().add(permission);
		}

		ModelMap model = new ModelMap();
		try {
			if(!operatorService.isUserNameExist(operator.getUserName())){
				operatorService.insertOperator(operator);
			}else{
				model.addAttribute("error", "用户名已经存在");
			}
		} catch (Exception e) {
			model.addAttribute("error", "操作失败，请刷新页面重试");
		}
		return model;
	}

	@RequestMapping(value = "/updateOperator", method = RequestMethod.POST)
	public @ResponseBody
	ModelMap updateOperator(@ModelAttribute("operator") Operator operator,
			String[] permissionID) {

		for (String id : permissionID) {
			Permission permission = new Permission();
			permission.setPermissionID(Integer.valueOf(id));
			operator.getPermissions().add(permission);
		}

		ModelMap model = new ModelMap();
		try {
			operatorService.updateOperator(operator);
			model.addAttribute("isSuccessfull", Boolean.TRUE);
		} catch (Exception e) {
			model.addAttribute("isSuccessfull", Boolean.FALSE);
		}
		return model;
	}

	@RequestMapping(value = "/operatorList")
	public ModelAndView operatorList(String pageIndex, ModelAndView model) {
		model.setViewName("configuration.operatorList");
		PagingBean<Operator> pagingBean = new PagingBean<Operator>();
		pagingBean.setCurrentPage(Integer.valueOf(pageIndex));
		try {
			operatorService.getPagingOperators(pagingBean);
			model.addObject("pagingBean", pagingBean);
		} catch (Exception e) {
			model.addObject("error", "取操作者数据失败");
		}
		return model;
	}

	@RequestMapping(value = "/editOperator")
	public @ResponseBody
	ModelMap editOperator(String operatorID) {
		ModelMap model = new ModelMap();
		Operator operator = new Operator();
		operator.setId(Integer.valueOf(operatorID));
		try {
			operatorService.loadOperator(operator);
		} catch (Exception e) {
			model.addAttribute("error", "读取失败");
		}
		model.addAttribute("operator", operator);
		return model;
	}

	@RequestMapping(value = "/deleteOperator")
	public @ResponseBody
	ModelMap deleteOperator(String operatorID) {
		ModelMap model = new ModelMap();
		Operator operator = new Operator();
		operator.setId(Integer.valueOf(operatorID));
		try {
			operatorService.deleteOperator(operator);
		} catch (Exception e) {
			model.addAttribute("error", "读取失败");
		}
		return model;
	}

	// Goods management

	@RequestMapping(value = "/insertGoods", method = RequestMethod.POST)
	public @ResponseBody
	ModelMap insertGoods(@ModelAttribute("goods") Goods goods,
			String[] permissionID) {

		ModelMap model = new ModelMap();
		try {
			if(goodsService.isGoodsNameNotExist(goods.getName())){
				goodsService.insertGoods(goods);
				model.addAttribute("isSuccessfull", Boolean.TRUE);
			}else{
				model.addAttribute("isSuccessfull", Boolean.FALSE);
				model.addAttribute("error", "商品名:"+goods.getName()+" 已经存在");
			}
		} catch (Exception e) {
			model.addAttribute("isSuccessfull", Boolean.FALSE);
			model.addAttribute("error", "添加失败，请重试。");
		}
		return model;
	}

	@RequestMapping(value = "/updateGoods", method = RequestMethod.POST)
	public @ResponseBody
	ModelMap updateGoods(@ModelAttribute("goods") Goods goods,
			String[] permissionID) {

		ModelMap model = new ModelMap();
		try {
			goodsService.updateOperator(goods);
		} catch (Exception e) {
			model.addAttribute("isSuccessfull", Boolean.FALSE);
		}
		model.addAttribute("isSuccessfull", Boolean.TRUE);
		return model;
	}

	@RequestMapping(value = "/goodsList")
	public ModelAndView goodsList(String pageIndex, ModelAndView model) {
		model.setViewName("configuration.goodsList");
		PagingBean<Goods> pagingBean = new PagingBean<Goods>();
		pagingBean.setCurrentPage(Integer.valueOf(pageIndex));
		try {
			goodsService.getPagingGoods(pagingBean);
			model.addObject("pagingBean", pagingBean);
		} catch (Exception e) {
			model.addObject("error", "取操作者数据失败");
		}
		return model;
	}

	@RequestMapping(value = "/editGoods")
	public @ResponseBody
	ModelMap editGoods(String goodsID) {
		ModelMap model = new ModelMap();
		Goods goods = new Goods();
		goods.setId(Integer.valueOf(goodsID));
		try {
			goodsService.loadGoods(goods);
			model.addAttribute("goods", goods);
		} catch (Exception e) {
			model.addAttribute("error", "读取失败");
		}
		return model;
	}

	@RequestMapping(value = "/deleteGoods")
	public @ResponseBody
	ModelMap deleteGoods(String goodsID) {
		ModelMap model = new ModelMap();
		Goods goods = new Goods();
		goods.setId(Integer.valueOf(goodsID));
		try {
			goodsService.deleteGoods(goods);
		} catch (Exception e) {
			model.addAttribute("error", "读取失败");
		}
		return model;
	}

	// department management

	@RequestMapping(value = "/insertDepartment", method = RequestMethod.POST)
	public @ResponseBody
	ModelMap insertDepartment(
			@ModelAttribute("department") Department department,
			String[] permissionID) {

		ModelMap model = new ModelMap();
		try {
			if(departmentService.isDepartmentNameNotExist(department.getDepartmentName())){
				departmentService.insertDepartment(department);
				model.addAttribute("isSuccessfull", Boolean.TRUE);
			}else{
				model.addAttribute("isSuccessfull", Boolean.FALSE);
				model.addAttribute("error","部门名："+department.getDepartmentName()+" 已经存在");
			}
		} catch (Exception e) {
			model.addAttribute("isSuccessfull", Boolean.FALSE);
			model.addAttribute("error","存储失败，请重试");
		}
		return model;
	}

	@RequestMapping(value = "/updateDepartment", method = RequestMethod.POST)
	public @ResponseBody
	ModelMap updateDepartment(@ModelAttribute("Department") Department department) {

		ModelMap model = new ModelMap();
		try {
			departmentService.updateDepartment(department);
		} catch (Exception e) {
			model.addAttribute("isSuccessfull", Boolean.FALSE);
		}
		model.addAttribute("isSuccessfull", Boolean.TRUE);
		return model;
	}

	@RequestMapping(value = "/departmentList")
	public ModelAndView departmentList(String pageIndex, ModelAndView model) {
		model.setViewName("configuration.departmentList");
		PagingBean<Department> pagingBean = new PagingBean<Department>();
		pagingBean.setCurrentPage(Integer.valueOf(pageIndex));
		try {
			departmentService.getPagingDepartment(pagingBean);
			model.addObject("pagingBean", pagingBean);
		} catch (Exception e) {
			model.addObject("error", "取操作者数据失败");
		}
		return model;
	}

	@RequestMapping(value = "/editDepartment")
	public @ResponseBody
	ModelMap editDepartment(String departmentID) {
		ModelMap model = new ModelMap();
		Department department = new Department();
		department.setId(Integer.valueOf(departmentID));
		try {
			departmentService.loadDepartment(department);
			model.addAttribute("department", department);
		} catch (Exception e) {
			model.addAttribute("error", "读取失败");
		}
		return model;
	}

	@RequestMapping(value = "/deleteDepartment")
	public @ResponseBody
	ModelMap deleteDepartment(String departmentID) {
		ModelMap model = new ModelMap();
		Department department = new Department();
		department.setId(Integer.valueOf(departmentID));
		try {
			departmentService.deleteDepartment(department);
		} catch (Exception e) {
			model.addAttribute("error", "读取失败");
		}
		return model;
	}
	
	@RequestMapping(value = "/deleteOldMemberData")
	public @ResponseBody
	ModelMap deleteOldMemberData(String dateTime) {
		ModelMap model = new ModelMap();
		memberService.deleteOldMemberData(dateTime);
		return model;
	}
	
	
	@RequestMapping(value = "/deleteBackupFiles")
	public @ResponseBody
	ModelMap deleteBackupFiles(String dateTime) {
		ModelMap model = new ModelMap();
		try {
			memberService.deleteBackupFiles(dateTime);
			model.addAttribute("success","success");
		} catch (Exception e) {
			model.addAttribute("error", e.getMessage());
		}
		return model;
	}
}
